package com.example.zhanghehe.myapplication

import android.opengl.GLES20
import android.opengl.GLSurfaceView
import android.opengl.Matrix
import android.util.Log
import java.nio.channels.FileLock
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.opengles.GL10

class MyGLRender:GLSurfaceView.Renderer {
    private val mViewMatrix=FloatArray(16)

    private val mMVPMatrix=FloatArray(16)

    private val mProjectionMatrix=FloatArray(16)

    private val mRotationMatrix=FloatArray(16)

     var mAngle: Float = 0.0f

    override fun onDrawFrame(p0: GL10?) {
        val scratch=FloatArray(16)
        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT or GLES20.GL_DEPTH_BUFFER_BIT)

        Matrix.setLookAtM(mViewMatrix,0,0f,0f,-3f,0f,0f,0f,0f,1.0f,0.0f)
        Matrix.multiplyMM(mMVPMatrix,0,mProjectionMatrix,0,mViewMatrix,0)
        mSquare.draw(mMVPMatrix)

        Matrix.setRotateM(mRotationMatrix,0,mAngle,0f,0f,1.0f)
        Matrix.multiplyMM(scratch,0,mMVPMatrix,0,mRotationMatrix,0)
        mTriangle.draw(scratch)
    }

    override fun onSurfaceChanged(p0: GL10?, p1: Int, p2: Int) {
        GLES20.glViewport(0,0,p1,p2 )

        val ratio=p1/p2.toFloat()
        Matrix.frustumM(mProjectionMatrix,0,-ratio,ratio,-1f,1f,3f,7f)

    }

    private lateinit var mTriangle: Triangle

    private lateinit var mSquare: Square

    override fun onSurfaceCreated(p0: GL10?, p1: EGLConfig?) {
        GLES20.glClearColor(0.0f,0.0f,0.0f,1.0f)
        mTriangle=Triangle()
        mSquare=Square()
    }

    companion object {
        private val TAG=MyGLRender::class.simpleName

        fun checkGlError(glOperation:String){
            var error=GLES20.glGetError()
            while (error  != GLES20.GL_NO_ERROR) {
                Log.e(TAG,"${glOperation} : glError ${error}")
            }
        }

        fun loadShader(type:Int,shaderCode:String): Int {
            val shader=GLES20.glCreateShader(type)
            GLES20.glShaderSource(shader,shaderCode)
            GLES20.glCompileShader(shader)
            return shader
        }
    }

}
